var express = require('express');
var router = express.Router();

const fileMap = new Map();

router.all('/', function(req, res, next) {
    req.peTime = new Date().getTime();
    return next();
});
/* GET users listing. */
router.get('/', function(req, res, next) {
    let { upload_to, name, chunk, chunks } = req.query;
    res.send(new Message(false, req.peTime, 'not_exists'));
});

//过滤器
function fileFilter(req, file, cb) {
    let { id, type, lastModifiedDate, upload_to, name, size, chunks, chunk } = req.body;
    file.savePath = path.join(upload_to, name); //储存文件路径
    file.chunk = chunk;
    if (!chunks) { //未分段上传
        return cb(null, true);
    } else {
        //计算文件信息md5取得唯一id;
        let sign = md5(id + name + type + lastModifiedDate + upload_to + size + chunks);
        req.filePak = fileMap.get(sign) || new FilePak(req.body, sign);
        fileMap.set(sign, req.filePak);
        return cb(null, true);
    }
}

//处理文件
router.post('/', bin.single('file'), function(req, res, next) {
    const { filePak, file, peTime } = req;
    //如果没有文件
    if (!file) return res.send(new Message(false, peTime, 'no-file'));
    console.log('分段接收完成:' + file.chunk);
    if (!filePak) { //只有一个分段
        fs.renameSync(file.path, file.savePath);
        let message = new Message(true, peTime, 'upload_success');
        message.info = file.savePath;
        res.send(message);
    } else {
        let b = filePak.addChunkData(file, file.chunk);
        if (b) {
            filePak.save().then((p) => {
                fileMap.delete(filePak.sign);
                let message = new Message(true, peTime, 'upload_success');
                message.info = p;
                return res.send(message);
            }).catch((err) => {
                console.log('文件合并出错');
                console.log(err);
                let message = new Message(false, peTime, '合并文件出错');
                return res.send(message);
            })
        } else {
            return res.send(new Message(true, peTime, 'upload_success'));
        }
    }
});

module.exports = router;